<?php


namespace app\cms\model\merchant;


use app\cms\community\lib\QueryModel;
use app\cms\dto\merchant\merchantInfo;
use app\cms\model\userModel;
use iflow\Response;
use think\facade\Db;
use think\Model;

class merchantModel extends QueryModel
{

    protected $table = "merchant_table";

    public function hasUser(): \think\model\relation\HasOne
    {
        return $this->hasOne(userModel::class, 'uid', 'uid');
    }

    /**
     * 获取指定用户商户信息 (带 用户信息)
     * @param int $uid
     * @param bool $saveToSession
     * @return Response
     */
    public function getMerchant(int $uid, bool $saveToSession = false): Response
    {
        $merchant = $this->withJoin([
            'hasUser' => [
                'user_group_id' => 'user_group_id',
                'nick_name' => 'nick_name',
                'avatar' => 'avatar',
                'signature' => 'signature',
            ]
        ], 'LEFT') -> where([
            'merchant_table.uid' => $uid
        ]) -> findOrEmpty();

        if ($merchant -> isEmpty()) {
            return message() -> nodata('暂无商户信息');
        }

        // 验证是否需要存入session
        if ($saveToSession) {
            session('merchant', $merchant -> toArray());
        }
        return message() -> success('查询成功', $merchant);
    }

    /**
     * 获取商户列表
     * @param string $merchant_name
     * @param int $merchant_type
     * @param int $status
     * @return Response
     * @throws \think\db\exception\DbException
     */
    public function getMerchantList(string $merchant_name, int $merchant_type, int $status = 1): Response
    {

        $where = [];

        if ($merchant_type > 0) {
            $where['merchant_type'] = $merchant_type;
        }

        if ($status >= 0) {
            $where['status'] = $status;
        }

        $query = $this->where($where);

        if ($merchant_name !== '') {
            $query -> whereLike('merchant_name', "%{$merchant_name}%");
        }

        return $query -> paginateQuery($query);
    }

    /**
     * 查询指定用户商户信息商户
     * @param int $uid
     * @return array|Model
     */
    public function findMerchant(int $uid): array|Model {
        return $this->where([ 'uid' => $uid ]) -> findOrEmpty();
    }

    /**
     * 创建商户信息
     * @param merchantInfo $merchantInfo
     * @return Response
     */
    public function createMerchant(merchantInfo $merchantInfo): Response {
        if (
            $this->where([
                'merchant_name' => $merchantInfo -> merchant_name
            ]) -> findOrEmpty() -> isExists()
        ) return message() -> parameter_error('商户名称已存在，请重试');

        $createData = self::create([
            'uid' => $merchantInfo -> getUid(),
            'merchant_name' => $merchantInfo -> merchant_name,
            'merchant_logo' => $merchantInfo -> merchant_logo,
            'merchant_hgraph' => $merchantInfo -> merchant_hgraph,
            'merchant_desc' => $merchantInfo -> merchant_desc,
            'merchant_introduction' => $merchantInfo -> merchant_introduction,
            'merchant_address' => $merchantInfo -> merchant_address,
            'lng' => $merchantInfo -> lng,
            'lat' => $merchantInfo -> lat,
            'merchant_type' => $merchantInfo -> merchant_type
        ]) -> toArray();

        if ($createData) {
            return message() -> success('申请成功， 等待审核中');
        }
        return message() -> update_failed('申请失败， 请稍后重试');
    }

    /**
     * 更新商户信息
     * @param merchantInfo $merchantInfo
     * @return Response
     */
    public function updateMerchant(merchantInfo $merchantInfo): Response {
        $update = self::update([
            'merchant_name' => $merchantInfo -> merchant_name,
            'merchant_logo' => $merchantInfo -> merchant_logo,
            'merchant_hgraph' => $merchantInfo -> merchant_hgraph,
            'merchant_desc' => $merchantInfo -> merchant_desc,
            'merchant_introduction' => $merchantInfo -> merchant_introduction,
            'merchant_address' => $merchantInfo -> merchant_address,
            'lng' => $merchantInfo -> lng,
            'lat' => $merchantInfo -> lat,
            'merchant_type' => $merchantInfo -> merchant_type
        ], [
            'uid' => $merchantInfo -> getUid(),
            'merchant_id' => $merchantInfo -> merchant_id
        ]) -> getChangedData();
        return message() -> success('更新成功', $update);
    }

    /**
     * 更改指定商户状态
     * @param int $merchant_id
     * @param int $status
     * @return Response
     */
    public function changeMerchantStatus(int $merchant_id, int $status): Response
    {
        $update = self::update([
            'status' => $status
        ], [
            'merchant_id' => $merchant_id
        ]) -> getChangedData();
        return message() -> success('更新成功', $update);
    }

    /**
     * 获取附近商户信息
     * @param string $lat 纬度
     * @param string $lng 经度
     * @param string $merchant_name 商户名称
     * @param int $merchant_type 商户类型
     * @return Response
     */
    public function getNearbyMerchant(string $lat, string $lng, string $merchant_name, int $merchant_type): Response
    {
        $distanceSql = str_replace("\r\n", "", "
            (6371 * acos(
                    cos (radians($lat)) * 
                    cos (radians(`merchant_model`.`lat`)) *
                    cos (radians(`merchant_model`.`lng`) - radians($lng)) + 
                    sin (radians($lat)) * sin((radians(`merchant_model`.`lat`)))
                )
            ) AS distance
        ");
        $query = $this-> withJoin([
            'hasUser' => [
                'user_group_id' => 'user_group_id',
                'nick_name' => 'nick_name',
                'avatar' => 'avatar',
                'signature' => 'signature',
            ]
        ], 'LEFT')
            -> field($distanceSql)
            -> where([
                'status' => 1
            ])
            -> having('distance <= 10')
            -> order([ 'distance' => 'desc' ]);

        if ($merchant_name !== '') {
            $query -> whereLike('merchant_name', "%{$merchant_name}%");
        }

        // 过滤商户类型
        if ($merchant_type) {
            $query -> where([ 'merchant_type' => $merchant_type ]);
        }

        $count = count($query -> query($query -> buildSql()));

        $lastPage = ceil($count / 12);
        $lastPage = max($lastPage, 1);
        $page = request() -> getParams('page') ?: 1;

        if ($lastPage < $page) return message() -> nodata('暂无数据');

        $sql = $query -> limit(($page * 12) - 12, 12) -> buildSql();
        return message() -> success('查询成功', $query -> query($sql), [
            'count' => $count,
            'page' => $lastPage,
        ]);
    }

    /**
     * 修改商户状态
     * @param int $merchant_id
     * @param int $status
     * @return Response
     */
    public function banOrUnblockMerch(int $merchant_id, int $status): Response {
        self::update([ 'status' => $status ], [ 'merchant_id' => $merchant_id ]);
        return message() -> success('更新成功');
    }
}